package cn.zf233.jwtshiro.config.shiro.sms;

import cn.zf233.jwtshiro.entity.User;
import cn.zf233.jwtshiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created by zf233 on 2021/7/12
 */
@Slf4j
public class VCodeRealm extends AuthorizingRealm {

    private final UserService userService;

    public VCodeRealm(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        VCodeToken token = (VCodeToken) authenticationToken;
        String phone = (String) token.getPrincipal();
        String vCode = (String) token.getCredentials();
        log.info("准备验证用户:'{}' (SMS)" + phone);
        String vCodeByPhone = userService.getVCodeByPhone(phone);
        User result = userService.getUserByPhone(phone);
        if (result == null) {
            log.info("用户不存在");
            throw new UnknownAccountException("不存在的用户");
        }
        if (StringUtils.isBlank(vCodeByPhone)) {
            log.info("用户信息验证失败，无效的验证码");
            throw new IncorrectCredentialsException("无效的验证码");
        }
        if (!vCodeByPhone.equals(vCode)) {
            log.info("用户信息验证失败，错误的验证码");
            throw new IncorrectCredentialsException("验证码有误");
        }
        log.info("用户信息验证通过");
        return new SimpleAuthenticationInfo(result, vCode, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof VCodeToken;
    }
}